package com.crm.framework.shiro.service;

import com.crm.common.utils.uuid.UUID;
import com.crm.system.domain.BieDoctor;
import com.crm.system.domain.BiePatient;
import com.crm.system.service.impl.BieDoctorServiceImpl;
import com.crm.system.service.impl.BiePatientServiceImpl;
import com.crm.system.service.impl.SysRoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.crm.common.constant.Constants;
import com.crm.common.constant.ShiroConstants;
import com.crm.common.constant.UserConstants;
import com.crm.common.core.domain.entity.SysUser;
import com.crm.common.utils.DateUtils;
import com.crm.common.utils.MessageUtils;
import com.crm.common.utils.ServletUtils;
import com.crm.common.utils.ShiroUtils;
import com.crm.framework.manager.AsyncManager;
import com.crm.framework.manager.factory.AsyncFactory;
import com.crm.system.service.ISysUserService;

import java.util.Date;

/**
 * 注册校验方法
 * 
 * @author crm
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;


    @Autowired
    private BieDoctorServiceImpl doctorService;

    @Autowired
    private BiePatientServiceImpl patientService;

    @Autowired
    private SysRoleServiceImpl roleService;
    /**
     * 注册
     */
    public String register(SysUser user)
    {

        //System.out.println(aNull);
        String aNull = common(1, user, Constants.REGISTER, MessageUtils.message("user.register.success"), "null");
        if(StringUtils.isEmpty(aNull)){
            //为空，注册成功
            //添加用户
            SysUser user1 = userService.selectUserByLoginName(user.getLoginName());
            try {
                //授权
                userService.insertUserAuth(user1.getUserId(), new Long[]{4L});
                //添加患者用户
                BiePatient biePatient=new BiePatient();
                biePatient.setUserId(user1.getUserId());
                biePatient.setPatientId(UUID.randomUUID().toString());
                patientService.insertBiePatient(biePatient);

                return "";
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();

            }
        }else{
            return aNull;
        }
    }

    private String common(Integer type,SysUser user,String constants,String message,String uuid){
        String msg = "", loginName = user.getLoginName(), password = user.getPassword();

        if (!StringUtils.isEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA)))
        { msg = "验证码错误"; }
        else if (StringUtils.isEmpty(loginName))
        { msg = "用户名不能为空"; }
        else if (StringUtils.isEmpty(password))
        { msg = "用户密码不能为空"; }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        { msg = "密码长度必须在5到20个字符之间"; }
        else if (loginName.length() < UserConstants.USERNAME_MIN_LENGTH
                || loginName.length() > UserConstants.USERNAME_MAX_LENGTH)
        { msg = "账户长度必须在2到20个字符之间"; }
        else if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(loginName)))
        { msg = "保存用户'" + loginName + "'失败，注册账号已存在"; }
        else
        {
            user.setPwdUpdateDate(DateUtils.getNowDate());
            user.setUserName(loginName);
            user.setSalt(ShiroUtils.randomSalt());
            user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
            int regFlag = userService.registerUser(user);
            //主键回填
            if (regFlag<0)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName,constants,message));
                if(type==1){
                    //默认用户，不授权
                    //TODO
                }else if(type==2){
                    //医生
                    int i = roleService.insertAuthUsers(3L, String.valueOf(user.getUserId()));

                    if(i<0){
                        msg="授权失败";
                    }else{
                        //更改医生表的user_id
                        BieDoctor bieDoctor=new BieDoctor();
                        bieDoctor.setDoctorId(uuid);
                        bieDoctor.setUserId(user.getUserId());
                        doctorService.updateBieDoctor(bieDoctor);
                    }
                }else if(type==3){
                    int i = roleService.insertAuthUsers(4L, String.valueOf(user.getUserId()));
                    //更改患者表的user_id
                    if(i<0){
                        msg="授权失败";
                    }else{
                        BiePatient patient=new BiePatient();
                        patient.setPatientId(uuid);
                        patient.setUserId(user.getUserId());
                        patientService.updateBiePatient(patient);
                    }
                }
            }
        }
        return msg;
    }

    /**
     * 管理员开通医生帐号，默认密码123456
     */
    public String registerDoctor(String uuid) {
        System.out.println(uuid);

        BieDoctor bieDoctor = doctorService.selectBieDoctorById(uuid);
        if (bieDoctor==null) return "医生不存在";
        //true为空
        else if(bieDoctor.getUserId()!=null){
            //不为空
            return "不允许注册，该用户已经存在登录帐号";
        }
        else{
            SysUser user=new SysUser();
            user.setPassword("123456");
            user.setLoginName(bieDoctor.getPhone());
            user.setUserName(bieDoctor.getDoctorName());
            user.setCreateBy("system");
            user.setCreateTime(new Date());
            return common(2,user,"管理员注册医生","管理员注册医生帐号成功",uuid);
        }

        //return null;
    }

    /**
     * 管理员开通患者帐号，默认密码123456
     */
    public String registerPatient(String uuid){
        BiePatient biePatient= patientService.selectBiePatientById(uuid);
        if (biePatient==null) return "患者不存在";
            //true为空
        else if(biePatient.getUserId()!=null){
            //不为空
            return "不允许注册，该用户已经存在登录帐号";
        }
        else{
            SysUser user=new SysUser();
            user.setPassword("123456");
            user.setLoginName(biePatient.getPhone());
            user.setUserName(biePatient.getPatientName());
            return common(3,user,"管理员注册患者","管理员注册患者帐号成功",uuid);
        }
    }

}
